﻿var list;
(function($){
    // 显示信息
    roleList();

    // 分页显示和数据表格
    function pagerFilter(data){
        if ($.isArray(data)){    // is array
            data = {
                total: data.length,
                rows: data
            }
        }
        var target = this;
        var dg = $(target);
        var state = dg.data('datagrid');
        var opts = dg.datagrid('options');
        if (!state.allRows){
            state.allRows = (data.rows);
        }
        if (!opts.remoteSort && opts.sortName){
            var names = opts.sortName.split(',');
            var orders = opts.sortOrder.split(',');
            state.allRows.sort(function(r1,r2){
                var r = 0;
                for(var i=0; i<names.length; i++){
                    var sn = names[i];
                    var so = orders[i];
                    var col = $(target).datagrid('getColumnOption', sn);
                    var sortFunc = col.sorter || function(a,b){
                        return a==b ? 0 : (a>b?1:-1);
                    };
                    r = sortFunc(r1[sn], r2[sn]) * (so=='asc'?1:-1);
                    if (r != 0){
                        return r;
                    }
                }
                return r;
            });
        }
        var start = (opts.pageNumber-1)*parseInt(opts.pageSize);
        var end = start + parseInt(opts.pageSize);
        data.rows = state.allRows.slice(start, end);
        return data;
    }
    var loadDataMethod = $.fn.datagrid.methods.loadData;
    var deleteRowMethod = $.fn.datagrid.methods.deleteRow;
    $.extend($.fn.datagrid.methods, {
        clientPaging: function(jq){
            return jq.each(function(){
                var dg = $(this);
                var state = dg.data('datagrid');
                var opts = state.options;
                opts.loadFilter = pagerFilter;
                var onBeforeLoad = opts.onBeforeLoad;
                opts.onBeforeLoad = function(param){
                    state.allRows = null;
                    return onBeforeLoad.call(this, param);
                }
                var pager = dg.datagrid('getPager');
                pager.pagination({
                    onSelectPage:function(pageNum, pageSize){
                        opts.pageNumber = pageNum;
                        opts.pageSize = pageSize;
                        pager.pagination('refresh',{
                            pageNumber:pageNum,
                            pageSize:pageSize
                        });
                        dg.datagrid('loadData',state.allRows);
                    }
                });
                $(this).datagrid('loadData', state.data);
                if (opts.url){
                    $(this).datagrid('reload');
                }
            });
        },
        loadData: function(jq, data){
            jq.each(function(){
                $(this).data('datagrid').allRows = null;
            });
            return loadDataMethod.call($.fn.datagrid.methods, jq, data);
        },
        deleteRow: function(jq, index){
            return jq.each(function(){
                var row = $(this).datagrid('getRows')[index];
                deleteRowMethod.call($.fn.datagrid.methods, $(this), index);
                var state = $(this).data('datagrid');
                if (state.options.loadFilter == pagerFilter){
                    for(var i=0; i<state.allRows.length; i++){
                        if (state.allRows[i] == row){
                            state.allRows.splice(i,1);
                            break;
                        }
                    }
                    $(this).datagrid('loadData', state.allRows);
                }
            });
        },
        getAllRows: function(jq){
            return jq.data('datagrid').allRows;
        }
    })

})(jQuery);

// 页面加载显示信息
function roleList() {
    $.ajax({
        url:"roleManagerList",
        data:"",
        type:"post",
        dataType:"json",
        success:function (data) {
            list = data
            $("#dg").datagrid({data:showRoleList(data)}).datagrid('clientPaging');
        },
        error:function (error) {
            alert("请求出错！")
        }
    });
}


// 获取当前时间
function CurentTime() {
    var now = new Date();

    var year = now.getFullYear();       //年
    var month = now.getMonth() + 1;     //月
    var day = now.getDate();            //日

    var hh = now.getHours();            //时
    var mm = now.getMinutes();          //分
    var ss = now.getSeconds();           //秒

    var clock = year + "-";

    if(month < 10)
        clock += "0";

    clock += month + "-";

    if(day < 10)
        clock += "0";

    clock += day + " ";

    if(hh < 10)
        clock += "0";

    clock += hh + ":";
    if (mm < 10) clock += '0';
    clock += mm + ":";

    if (ss < 10) clock += '0';
    clock += ss;
    return(clock);
}

    // 显示信息
function showRoleList(data) {
    var rows =[];
    for(var i=0;i<data.length;i++){
        var da = data[i];
        rows.push({
            roleName:da.rolename,
            creationTime:da.creationtime,
            isStart:da.isstart==1?"启用":"禁用",
            caoZuo:'<a href="javascript:void(0)" onclick="updateinfo('+da.id+')">修改</a>&nbsp;|&nbsp;' +
            '<a href="#" onclick="deleterole('+da.id+')">删除</a>'
        });
    }
    return rows;
}

// 添加角色
function add() {
    for(var i=0;i<list.length;i++){
        if($("#rolename").val() === list[i].rolename){
            alert("角色名已存在！")
            return;
        }
    }

    $.ajax({
        url: "addRole",
        data: {
            "rolename": $("#rolename").val(),
            "creationtime":CurentTime(),
            "createdby": $("#createdby").val(),
            "lastupdatetime":CurentTime(),
            "isstart": $("#isstart").val()
        },
        type: "post",
        dataType: "json",
        success: function (count) {
            if (count > 0) {
                $("#w").window('close');
                alert("添加成功！");
                roleList();
            } else {
                alert("添加失败！")
            }
        },
        error: function (error) {
            alert("请求出错！")
        }

    })
}

// 点击修改显示输入框
var idd;
function updateinfo(id) {
    $('#w').window('open');
    for(var i=0;i<list.length;i++){
        var das = list[i];
        if(das.id == id){
            idd = das.id;
            woerds = list[i];
        }
    }

    $("#rolename").val(woerds.rolename);
    $("#createdby").val(woerds.createdby);
    $("#isstart").val(woerds.isstart);

}

// 修改角色
function update() {

    $.ajax({
        url: "updateRole",
        data: {
            "id":idd,
            "rolename": $("#rolename").val(),
            "createdby": $("#createdby").val(),
            "lastupdatetime":CurentTime(),
            "isstart": $("#isstart").val()
        },
        type: "post",
        dataType: "json",
        success: function (count) {
            if (count > 0) {
                $("#w").window('close');
                alert("修改成功！");
                roleList();
            } else {
                alert("修改失败！")
            }
        },
        error: function (error) {
            alert("请求出错！")
        }
    })
}

// 删除信息
function deleterole(id) {
    if(confirm("是否删除？")){
        $.ajax({
            url:"deleteRole",
            data:"id="+id,
            type:"post",
            dataType:"json",
            success:function (count) {
                if(count > 0){
                    alert("删除成功！");
                    roleList();
                }else{
                    alert("删除失败！")
                }
            },
            error:function(error){
                alert("出现错误！");
            }
        });
    }


}